package com.zfk.framework.notification;

import com.zfk.framework.config.ConfigLoader;
import com.zfk.framework.models.config.Config;
import com.zfk.framework.models.config.DingTalk;
import com.zfk.framework.utils.MessageTemplate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 钉钉消息通知类
 * 用于向钉钉发送各种消息通知
 */
public class DingTalkNotifier {
    private static final Logger logger = LogManager.getLogger(DingTalkNotifier.class);

    /**
     * 发送钉钉消息
     *
     * @param message 消息内容
     */
    public static void sendMessage(String message) {
        Config config = ConfigLoader.getConfig();
        if (config == null) {
            logger.error("配置未加载，无法发送钉钉消息");
            return;
        }

        DingTalk dingTalk = config.getDingTalk();
        if (dingTalk == null || dingTalk.getWebhook() == null || dingTalk.getWebhook().isEmpty()) {
            logger.warn("钉钉webhook未配置，跳过发送消息");
            return;
        }

        String webhookUrl = dingTalk.getWebhook();
        String jsonMessage = String.format("{\"msgtype\": \"text\", \"text\": {\"content\": \"%s\"}}", message);

        sendHttpRequest(webhookUrl, jsonMessage);
    }

    /**
     * 发送测试报告通知
     *
     * @param reportUrl 报告地址
     */
    public static void sendTestReportNotification(String reportUrl) {
        Config config = ConfigLoader.getConfig();
        if (config == null) {
            logger.error("配置未加载，无法发送测试报告通知");
            return;
        }

        String projectName = config.getProjectName();
        String testerName = config.getTesterName();

        String message = String.format(
                MessageTemplate.TEST_REPORT_TEMPLATE,
                projectName, testerName,reportUrl
        );

        sendMessage(message);
    }

    /**
     * 发送HTTP请求到钉钉webhook
     *
     * @param webhookUrl webhook地址
     * @param message    消息内容（JSON格式）
     */
    private static void sendHttpRequest(String webhookUrl, String message) {
        try {
            URL url = new URL(webhookUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.setDoOutput(true);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = message.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                logger.info("钉钉消息发送成功");
            } else {
                logger.error("钉钉消息发送失败，响应码: {}", responseCode);
            }
        } catch (Exception e) {
            logger.error("发送钉钉消息时发生异常: ", e);
        }
    }
}